package properties

import (
	"github.com/spf13/viper"
	"os"
)

func init() {
	loadConfig()

	err := viper.UnmarshalKey(DatabasePrefix, &DatabaseConfig)
	if err != nil {
		panic(DatabasePrefix + " config err:" + err.Error())
	}

	err = viper.UnmarshalKey(AppPrefix, &AppConfig)
	if err != nil {
		panic(AppPrefix + " config err:" + err.Error())
	}

	err = viper.UnmarshalKey(NacosPrefix, &NacosConfig)
	if err != nil {
		panic(NacosPrefix + " config err:" + err.Error())
	}

	err = viper.UnmarshalKey(ElasticPrefix, &ElasticConfig)
	if err != nil {
		panic(ElasticPrefix + " config err:" + err.Error())
	}
}

func loadConfig() {
	profileType := os.Getenv("active.profile")
	if profileType == "" {
		viper.SetConfigType("yaml")
		viper.SetConfigFile("config/go-config.yml")
		err := viper.ReadInConfig()
		if err != nil {
			panic("go-config err:" + err.Error())
		}
		profile := viper.Get("active.profile")
		profileType = profile.(string)
	}

	configFile := "config/go-config-" + profileType + ".yml"
	viper.SetConfigFile(configFile)
	err := viper.ReadInConfig()
	if err != nil {
		panic(configFile + " err:" + err.Error())
	}
}
